package com.beasts.ant.auth.config.oauth.handler;

import com.beasts.ant.auth.common.constant.CommonConstant;
import com.beasts.ant.auth.common.dto.R;
import com.beasts.ant.auth.common.exception.AntDeniedException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 授权拒绝处理器，覆盖默认的OAuth2AccessDeniedHandler
 * 包装失败信息到AntDeniedException
 *
 * @author Locker
 * @date 07/05/2018 3:27 PM
 * @since 1.0
 */
@Component
public class SelfAccessDeniedHandler extends OAuth2AccessDeniedHandler {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 授权拒绝处理，使用R包装
     */
    public void handler(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        response.setCharacterEncoding(CommonConstant.UTF8);
        response.setContentType(CommonConstant.CONTENT_TYPE);
        R<String> result = new R<>(new AntDeniedException("授权失败，禁止访问"));
        response.setStatus(403);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(request));
    }

}
